﻿using Autofac;
using Infrastructure.Attributes.Ioc;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Model
{
    public static class AutofacIocManger
    {
        /// <summary>
        /// 批量注入扩展
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="assembly"></param>
        public static void BatchAutowired( ContainerBuilder builder, params Assembly[] assembly)
        {

            List<Type> Types = new List<Type>();
            foreach (Assembly a in assembly)
            {
                Types.AddRange(a.GetTypes());
            }


            //瞬时注入
            builder.RegisterTypes(Types.Where(t => t.IsClass && !t.IsAbstract && t.GetCustomAttribute<ComponentAttribute>()?.Lifetime == ServiceLifetime.Transient).ToArray())
                .AsSelf()//这里可以注册成为接口类型
                .AsImplementedInterfaces()
                .InstancePerDependency()
                .PropertiesAutowired(new AutofacAutowiredPropertySelector()); //不过滤了
                                                                              //.PropertiesAutowired();
                                                                              //单例注入
            builder.RegisterTypes(Types.Where(t => t.IsClass && !t.IsAbstract && t.GetCustomAttribute<ComponentAttribute>()?.Lifetime == ServiceLifetime.Singleton).ToArray())
               .AsSelf()
               .AsImplementedInterfaces()
               .SingleInstance()
               .PropertiesAutowired(new AutofacAutowiredPropertySelector()); //不过滤了
                                                                             //.PropertiesAutowired();
                                                                             //生命周期注入


            var aasdf = Types.Where(t => t.IsClass && !t.IsAbstract && t.GetCustomAttribute<ComponentAttribute>()?.Lifetime == ServiceLifetime.Scoped).ToArray();


            builder.RegisterTypes(Types.Where(t => t.IsClass && !t.IsAbstract && t.GetCustomAttribute<ComponentAttribute>()?.Lifetime == ServiceLifetime.Scoped).ToArray())
           .AsSelf()
           .AsImplementedInterfaces()
           .InstancePerLifetimeScope()
           .PropertiesAutowired(new AutofacAutowiredPropertySelector());//不过滤了
                                                                        //.PropertiesAutowired();

        }
    }
}
